package com.guoxin.part1.chapter3;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author guoxin
 * @date 2019/8/27
 */
public class FigthQueryExample {
    private static List<String> fightCompany = Arrays.asList("CSA", "CEA", "HNA");

    public static void main(String[] args) {
        List<String> results = search("SH", "BJ");
        System.out.println("==========");
        results.forEach(System.out::println);
    }

    private static List<String> search(String original, String dest) {
        final List<String> result = new ArrayList<>();
        /*List<FigthQueryTask> tasks = fightCompany.stream().map(f -> createSearchTask(f, original, dest)).collect(Collectors.toList());
        tasks.forEach(Thread::start);
        tasks.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        tasks.stream().map(FigthQueryTask::get).forEach(result::addAll);
        return result;*/
        List<FigthQueryTask> tasks = new ArrayList<>();
        for (String airline : fightCompany) {
            FigthQueryTask searchTask = createSearchTask(airline, original, dest);
            tasks.add(searchTask);
        }
        tasks.forEach(Thread::start);
        tasks.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        tasks.forEach(t -> result.addAll(t.get()));
        return result;
    }

    private static FigthQueryTask createSearchTask(String fight, String original, String dest) {
        return new FigthQueryTask(fight, original, dest);
    }
}
